package com.jackrain.nea.shiro.stateful;

import com.jackrain.nea.core.query.QueryException;
import com.jackrain.nea.util.ShiroSessionUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.util.WebUtils;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.security.SecurityWebUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * Created by Lucky dog on 2016/7/19.
 */

@Component
public  class MonitorRealm extends AuthorizingRealm {

    //获取身份验证相关信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        /* 这里编写登陆认证代码 */
        ValueHolder vh = new ValueHolder();
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        User user = null;
        Subject subject = SecurityUtils.getSubject();
        Locale locale=LocaleContextHolder.getLocale();
        try {
            user = SecurityWebUtils.getUser(token.getUsername());

        } catch (QueryException e) {
            e.printStackTrace();
        }
        ((UserImpl)user).setLocale(locale);

        if(user == null || user.getId() == null){
            vh.put("code",-1);
            vh.put("message", "用户名不正确");
            ShiroSessionUtil.setAttribute("vh",vh);
            throw new UnknownAccountException("No account found for user。。。。");
        }
        String tokPassword = String.valueOf(token.getPassword());
        String password = WebUtils.encryptBasedDes(tokPassword, user.getPwdrand().getBytes());
        token.setPassword(password.toCharArray());
        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPasswordHash(), getName());
        return  info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//        String name = (String)principals.getPrimaryPrincipal();
//        Set<String> set = new HashSet<String>();
//        set.add("admin");
//        User user = null;
//        try {
//            user = SecurityWebUtils.getUser(name);
//        } catch (QueryException e) {
//            e.printStackTrace();
//        }
//        if(user != null){
//            return new SimpleAuthorizationInfo(set);
//        }
        return null;
    }



}